import axios from 'axios'
import {ElMessage} from 'element-plus';
import {useUserStore} from "@/store/user";
import router from "@/router";

const request = axios.create({
    baseURL: 'http://localhost:8888',
    timeout: 5000
})

// request 拦截器
// 可以自请求发送前对请求做一些处理
// 比如统一加token，对请求参数统一加密
request.interceptors.request.use(config => {
    config.headers['Content-Type'] = 'application/json;charset=utf-8';
    const userStore = useUserStore()
    let token = userStore.loginInfo.token
    if (token) {
        config.headers.Authorization = `${token}`
    }
    return config
}, error => {
    return Promise.reject(error)
});

// response 拦截器
// 响应后统一处理结果
request.interceptors.response.use(
    respose => {
        if (respose.data.code == 501 && respose.data.message == '身份认证已过期，请重新登录') {
            ElMessage({type: 'error', message: respose.data.message})
            router.push({path: '/login'})
        }
        return respose.data
    }, error => {
        console.log(error)
        const status = error.response.status
        if (status === 500) {
            const userStore = useUserStore()
            userStore.loginInfo.value = {}
            router.push({path: '/login'})
        }
        ElMessage({type: 'error', message: error.response.message})
        return Promise.reject(error)
    }
)

export default request

